class ImageWall {
    constructor() {
        this.imageWall = document.getElementById('imageWall');
        this.loading = document.getElementById('loading');
        this.noImages = document.getElementById('noImages');
        this.imageCount = document.getElementById('imageCount');
        this.directoryInput = document.getElementById('directoryInput');
        this.loadImagesBtn = document.getElementById('loadImages');
        this.refreshImagesBtn = document.getElementById('refreshImages');
        this.modal = document.getElementById('imageModal');
        this.modalImage = document.getElementById('modalImage');
        this.modalTitle = document.getElementById('modalTitle');
        this.modalDetails = document.getElementById('modalDetails');
        this.closeModal = document.querySelector('.close');

        this.initEventListeners();
        this.loadImages(); // Load default images on startup
    }

    initEventListeners() {
        this.loadImagesBtn.addEventListener('click', () => this.loadImages());
        this.refreshImagesBtn.addEventListener('click', () => this.loadImages());
        
        this.directoryInput.addEventListener('keypress', (e) => {
            if (e.key === 'Enter') {
                this.loadImages();
            }
        });

        this.closeModal.addEventListener('click', () => this.hideModal());
        this.modal.addEventListener('click', (e) => {
            if (e.target === this.modal) {
                this.hideModal();
            }
        });

        document.addEventListener('keydown', (e) => {
            if (e.key === 'Escape') {
                this.hideModal();
            }
        });
    }

    async loadImages() {
        this.showLoading();
        
        try {
            const customDir = this.directoryInput.value.trim();
            const apiUrl = customDir ? `/api/images/${encodeURIComponent(customDir)}` : '/api/images';
            
            const response = await fetch(apiUrl);
            const images = await response.json();
            
            this.hideLoading();
            this.displayImages(images);
        } catch (error) {
            console.error('Error loading images:', error);
            this.hideLoading();
            this.showNoImages();
        }
    }

    displayImages(images) {
        this.imageWall.innerHTML = '';
        
        if (images.length === 0) {
            this.showNoImages();
            return;
        }

        this.hideNoImages();
        this.updateImageCount(images.length);

        images.forEach(image => {
            const imageItem = this.createImageItem(image);
            this.imageWall.appendChild(imageItem);
        });
    }

    createImageItem(image) {
        const imageItem = document.createElement('div');
        imageItem.className = 'image-item';
        
        const img = document.createElement('img');
        img.src = image.path;
        img.alt = image.name;
        img.loading = 'lazy';
        
        // Handle image load errors
        img.onerror = () => {
            img.src = '';
            img.alt = '图片加载失败';
        };

        const imageInfo = document.createElement('div');
        imageInfo.className = 'image-info';
        
        const title = document.createElement('h3');
        title.textContent = image.name;
        
        const details = document.createElement('p');
        details.textContent = `${this.formatFileSize(image.size)} • ${this.formatDate(image.modified)}`;
        
        imageInfo.appendChild(title);
        imageInfo.appendChild(details);
        
        imageItem.appendChild(img);
        imageItem.appendChild(imageInfo);
        
        // Add click event to show modal
        imageItem.addEventListener('click', () => this.showModal(image));
        
        return imageItem;
    }

    showModal(image) {
        this.modalImage.src = image.path;
        this.modalTitle.textContent = image.name;
        this.modalDetails.textContent = `文件大小: ${this.formatFileSize(image.size)} | 修改时间: ${this.formatDate(image.modified)}`;
        this.modal.classList.remove('hidden');
        document.body.style.overflow = 'hidden';
    }

    hideModal() {
        this.modal.classList.add('hidden');
        document.body.style.overflow = 'auto';
    }

    showLoading() {
        this.loading.classList.remove('hidden');
        this.imageWall.classList.add('hidden');
        this.noImages.classList.add('hidden');
    }

    hideLoading() {
        this.loading.classList.add('hidden');
        this.imageWall.classList.remove('hidden');
    }

    showNoImages() {
        this.noImages.classList.remove('hidden');
        this.imageWall.classList.add('hidden');
        this.updateImageCount(0);
    }

    hideNoImages() {
        this.noImages.classList.add('hidden');
    }

    updateImageCount(count) {
        this.imageCount.textContent = `${count} 张图片`;
    }

    formatFileSize(bytes) {
        if (bytes === 0) return '0 Bytes';
        const k = 1024;
        const sizes = ['Bytes', 'KB', 'MB', 'GB'];
        const i = Math.floor(Math.log(bytes) / Math.log(k));
        return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i];
    }

    formatDate(dateString) {
        const date = new Date(dateString);
        return date.toLocaleDateString('zh-CN') + ' ' + date.toLocaleTimeString('zh-CN', { 
            hour: '2-digit', 
            minute: '2-digit' 
        });
    }
}

// Initialize the image wall when DOM is loaded
document.addEventListener('DOMContentLoaded', () => {
    new ImageWall();
});
